import { DownOutlined } from '@ant-design/icons';
import { isDocument } from '@testing-library/user-event/dist/utils';
import { useEffect,useState } from 'react';
import MyddStyle from './Mydropdown.module.scss';
import ReactDOM from 'react-dom';
import { all } from 'axios';
export default function Mydropdown (props){
    const [isShow, setIsShow] = useState(false)
    const [container, setContainer] = useState(null); 
    // const [curEl, setEl] = useState(null)
    useEffect(() => {    
        // 创建一个新的 div 元素     
        const newContainer = document.createElement('div');     
        // 将新的 div 元素添加到 body 节点上     
        document.body.appendChild(newContainer);     
        // 设置状态     
        setContainer(newContainer);  
        // 监听window变化
        function watchResize(){
            setIsShow(false)
        }
        window.addEventListener('resize',watchResize)
        // 组件卸载时，从 body 节点上移除 div 元素     
        return () => {       
            document.body.removeChild(newContainer);
            window.removeEventListener('resize',watchResize)  
        };
    }, []);  
    return <div className={MyddStyle['my-dropdown-box']}>
        <div onClick={(e)=>{
            if(!isShow){
                setIsShow(true)
            }
            const DOMrect = e.currentTarget.getBoundingClientRect() 
            setTimeout(() => {
                const allUl = document.querySelector('.'+MyddStyle['my-dropdown-item-box'])
                if(allUl?.length === 0) {return}
                allUl.style.left = DOMrect.left + 'px'
                allUl.style.top = DOMrect.top+30 + 'px'
                if(isShow){
                    setIsShow(false)
                }
            }, 250);
        }} className={MyddStyle['my-dropdown-title']}>{ props.children }</div>
        { isShow?ReactDOM.createPortal(<ul className={MyddStyle['my-dropdown-item-box']}>
            {props?.menu.map(item=>{
                return <li key={item.key} onClick={()=>{
                    setIsShow(!isShow)
                    props.onOperate&&props.onOperate(item)
                }}> { item.label }</li>
            })}
        </ul>,container): null }
    </div>
}